<template>
  <el-dialog
      v-model="visible"
      title="保存为基金组合"
      width="500px"
      @close="resetForm"
  >
    <el-form label-position="top">
      <el-form-item label="组合名称">
        <el-input v-model="portfolioName" placeholder="请输入组合名称" />
      </el-form-item>
      <el-form-item label="组合描述">
        <el-input v-model="portfolioDesc" type="textarea" placeholder="可填写策略、目标等" />
      </el-form-item>
      <el-form-item label="已选基金">
        <el-tag
            v-for="code in fundCodes"
            :key="code"
            type="primary"
            size="small"
            style="margin: 4px;"
        >
          {{ code }}
        </el-tag>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleSave">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

// Props
const props = defineProps({
  modelValue: Boolean,
  fundCodes: {
    type: Array,
    required: true
  },
  userId: {
    type: Number,
    required: true
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'saved'])

const visible = ref(props.modelValue)
watch(() => props.modelValue, val => visible.value = val)
watch(visible, val => emit('update:modelValue', val))

const portfolioName = ref('')
const portfolioDesc = ref('')

const resetForm = () => {
  portfolioName.value = ''
  portfolioDesc.value = ''
}

const handleSave = async () => {
  if (props.fundCodes.length === 0) {
    ElMessage.warning('请至少选择一个基金')
    return
  }

  try {
    await axios.post('/api/portfolio/save', {
      userId: props.userId,
      name: portfolioName.value,
      description: portfolioDesc.value,
      fundCodes: props.fundCodes
    })
    ElMessage.success('保存成功！')
    visible.value = false
    emit('saved')
  } catch (err) {
    ElMessage.error('保存失败：' + (err.response?.data?.message || err.message))
  }
}
</script>
